package com.example.fenye1.service.Impl;

import com.alibaba.fastjson.JSON;
import com.example.fenye1.dao.UserMapper;
import com.example.fenye1.entity.PageRequest;
import com.example.fenye1.entity.PageResult;
import com.example.fenye1.entity.User;
import com.example.fenye1.service.UserService;
import com.example.fenye1.utils.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public PageResult findUserByPage(PageRequest pageRequest) {
        return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest));
    }

    @Override
    public String deleteById(Integer id) {

        int delNum = userMapper.deleteById(id);

        HashMap<String, Integer> map = new HashMap<>();
        map.put("code", delNum);
        if (delNum == 1) {
            map.put("status", 200);
        } else {
            map.put("status", 600);
        }
        return JSON.toJSONString(map);
    }

    /**
     * 调用分页插件完成分页
     */
    private PageInfo<User> getPageInfo(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectUserPage();
        return new PageInfo<>(users);
    }
}
